class PrintVersionWebpackPlugin {
  constructor () {
    let commitId = ''
    try {
      commitId = require('child_process').execSync('git rev-parse HEAD').toString().trim().substr(0, 6)
      commitId = `.${commitId}`
    } catch (err) {
      // eslint-disable-next-line no-console
      console.log(err)
    }
    this.version = require('../../../package.json').version + commitId
    this.nowDateTime = new Date()
  }

  apply (compiler) {
    if (compiler.hooks && process.env.NODE_ENV === 'production') {
      compiler.hooks.done.tap('print-version-webpack-plugin', () => {
        const nowDate = new Date()
        const totalTime = ((nowDate.getTime() - this.nowDateTime.getTime()) / 1000).toFixed(2) + 's'
        setTimeout(() => {
          // eslint-disable-next-line no-console
          console.log('\x1B[32m%s\x1B[39m', `
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*
++++                    开始时间：${this.nowDateTime.toLocaleString()}
++++                    结束时间：${nowDate.toLocaleString()}
++++                    打包耗时：${totalTime}
++++                    打包版本：v${this.version}
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*
              `)
        }, 500)
      })
    }
  }
}

module.exports = PrintVersionWebpackPlugin